<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>next-tick</title>
</head>

<body>
    <script>
        let pending = false
        const tasks = []
        const flushCallbacks = () => {
            pending = false
            tasks.forEach(task => task())
            tasks.length = 0
        }

        const p = Promise.resolve()
        const timerFunc = () => {
            p.then(flushCallbacks)
        }

        function nextTick(task) {
            tasks.push(task)
            if (!pending) {
                pending = true
                timerFunc()
            }
        }

        const task1 = () => console.log('1')
        const task2 = () => console.log('2')

        console.log('before')
        nextTick(task1)
        nextTick(task2)
        console.log('after')
    </script>
</body>

</html>